package com.subumbo.audio.processing 
{
	
	import __AS3__.vec.Vector;
	
	import flash.utils.ByteArray;	

	/**
	 * Simple delay line with a static read offset (max: size of delay line - 1)
	 * 
	 * @author Andre Michelle
	 */
	public class TinyDelay 
	{
		private const delaySize: int = ( 1000 * 44.1 ); // max 1000ms @44.1KHz
		private const delayLine: Vector.<Vector.<Number>> = new Vector.<Vector.<Number>>( 2, true );
		
		private var _delayOffset: int;
		private var _wetLevel: Number;
		private var _feedback: Number;
		
		private var _writeIndex: int;
		
		public function TinyDelay( delayOffset: int, wetLevel: Number, feedback: Number )
		{
			if( delayOffset >= delaySize )
				throw new RangeError();
			
			_delayOffset = delayOffset;
			_wetLevel = wetLevel;
			_feedback = feedback;
			
			delayLine[0] = new Vector.<Number>( delaySize, true );
			delayLine[1] = new Vector.<Number>( delaySize, true );
			
			_writeIndex = 0;
		}
		
		public function process(samples:ByteArray):void
		
		{
			var leDelayLine: Vector.<Number> = delayLine[0];
			var riDelayLine: Vector.<Number> = delayLine[1];

			var leBuffer:ByteArray = samples;
			var riBuffer:ByteArray = samples;
			
			var readIndex: int;
			
			var i: int = 0;
			var n: int = 2048;
			
			for( ; i < n ; ++i )
			{
				//-- read at the end of the delay line
				readIndex = _writeIndex - _delayOffset;
				
				//-- clamp
				if( readIndex < 0 )
					readIndex += delaySize;
					
				//-- write input to delay line (replace)
				leDelayLine[ _writeIndex ] = leBuffer[i];
				riDelayLine[ _writeIndex ] = riBuffer[i];
				
				//-- write read feedback to delay line (add)
				leDelayLine[ _writeIndex ] += leDelayLine[ readIndex ] * _feedback;
				leDelayLine[ _writeIndex ] += riDelayLine[ readIndex ] * _feedback;

				//-- write read amplitudes into buffer (add > dry level = 1.0)
				leBuffer[i] += leDelayLine[ readIndex ] * _wetLevel;
				riBuffer[i] += riDelayLine[ readIndex ] * _wetLevel;
				
				//-- move write head
				if( ++_writeIndex == delaySize )
					_writeIndex = 0;
			}
		}
	}
}